import axios from 'axios'
// import {useRouter} from "vue-router";
// const router = useRouter();
// import router from '../router'
import { ElMessage } from 'element-plus'
const baseURL = 'https://api.459n.com';
axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 180000;//设置超时时间
axios.defaults.headers.post['Content-Type'] = 'application/json';
let token = localStorage.getItem('token');
if (token) {
    axios.defaults.headers['Authorization'] = 'Bearer '+ token;
}

//封装请求拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    config.headers['Authorization'] = 'Bearer '+localStorage.getItem('token');
    config.params = { ...config.params, timestamp: getCurrentUnixTimestamp() }; // 添加参数到请求体
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});


//封装响应拦截器
axios.interceptors.response.use(function (response) {
    // console.log(response.data)
    let res = response.data;
    // if(response.data.code == 400){
    //     router.push('/login');
    // }
    //只返回200
    if(res.code === 200){
        return res;
    }
    // else if(res.code === 401){
    //     // alert(res.msg)
    //     ElMessage({
    //         message: res.msg,
    //         grouping: true,
    //         type: 'error',
    //       })
    //     console.log(router)
    //     router.push({path:'/login'})
    // }
    else if(res.code === 404){
        // alert(res.msg)
        ElMessage({
            message: res.msg,
            grouping: true,
            type: 'warning',
          })
    }
    return response
}, function (error) {
    console.log(error);
    // 对响应错误做点什么
    return Promise.reject(error);
})
// 获取当前 Unix 时间戳的函数
function getCurrentUnixTimestamp() {
    return Math.floor(Date.now() / 1000);
  }
export function api( url, params,method = 'post'){
    switch (method.toLowerCase()) {
        case 'get':
          return axios.get(url, { params });
        case 'post':
          return axios.post(url, params);
        case 'put':
          return axios.put(url, params);
        case 'delete':
          return axios.delete(url, { data: params });
        default:
          throw new Error(`Unsupported method: ${method}`);
      }
    // return axios[method](url, params)
}